package cn.topcodes.tcsf.wechat.service;

import cn.topcode.unicorn.wxsdk.WXContext;
import cn.topcode.unicorn.wxsdk.material.MaterialInvoker;
import cn.topcode.unicorn.wxsdk.material.dto.UploadForeverMaterialResult;
import cn.topcodes.tcsf.admin.commons.generic.GenericService;
import cn.topcodes.tcsf.wechat.domain.entity.WechatMp;
import cn.topcodes.tcsf.wechat.domain.entity.WechatPicture;
import cn.topcodes.tcsf.wechat.service.utils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;

/**
 * 图片素材 服务
 * @author xw
 * @date 2017-12-22 15:14:00
 */
@Service
@Transactional(readOnly = true)
public class WechatPictureServiceImpl extends GenericService<WechatPicture> implements WechatPictureService {

    @Autowired
    private WechatMpService wechatMpService;

    private MaterialInvoker invoker = WXContext.getMaterialInvoker();

    @Autowired
    private WechatFileService wechatFileService;

    @Override
    @Transactional(readOnly = false)
    public void upload(String mpId, File file) {
        WechatPicture picture = new WechatPicture();

        picture.setName(file.getName());
        picture.setUrl("/picture/" + file.getName());

        UploadForeverMaterialResult result = invoker.uploadForeverImageMaterial(mpId, file);
        if (result.getErrcode() == 0) {
            picture.setMediaId(result.getMediaId());
            picture.setPicUrl(result.getUrl());
            WechatMp wechatMp = wechatMpService.findWechatMpByMpId(mpId);
            picture.setWechatMpId(wechatMp.getId());
            this.create(picture);
        } else {
                throw new IllegalArgumentException("errcode: " + result.getErrcode() + ", errmsg: " + result.getErrmsg());
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void upload(File file) {
        this.upload(wechatMpService.getDefaultMpId(), file);
    }

    @Override
    @Transactional(readOnly = false)
    public void update(WechatPicture picture) {
        WechatPicture p = this.findOne(picture.getId());
        if (p != null) {
            BeanUtils.copyProperties(p, picture);
            super.update(p);
        }
    }

    @Override
    @Transactional(readOnly = false)
    public WechatPicture delete(Long id) {
        WechatPicture picture = this.findOne(id);
        if (picture != null) {
            String mpId = wechatMpService.getMpId(picture.getWechatMpId());
            String url = picture.getUrl();
            wechatFileService.deleteFile(
                    WechatFileService.FILE_TYPE_PICTURE, wechatFileService.getNameByUrl(url, "/"));
            invoker.deleteForeverMaterial(mpId, picture.getMediaId());
            return super.delete(id);
        }
        return null;
    }
}
